%%%-------------------------------------------------------------------
%%% @author wukai
%%% @copyright (C) 2020, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 02. 9月 2020 1:17 下午
%%%-------------------------------------------------------------------
-module(himq).
-author("wukai").

%% API
-export([]).
-export([to_binary/1,uuid/1]).

-export([md5/1]).
-export([timestamp/0, local_time/0, datetime_to_timestamp/1, timestamp_to_datetime/1,page_data/3]).

%%获取时间戳
timestamp() ->
  {M, S, _} = os:timestamp(),
  M * 1000000 + S.
%%本地时间
local_time() -> calendar:local_time().

datetime_to_timestamp(DateTime) ->
  calendar:datetime_to_gregorian_seconds(DateTime) -
    calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}}).

%%时间戳转时间
timestamp_to_datetime(Timestamp) ->
  calendar:gregorian_seconds_to_datetime(Timestamp +
    calendar:datetime_to_gregorian_seconds({{1970, 1, 1}, {0, 0, 0}})).

to_binary(Source) when is_list(Source) -> list_to_binary(Source);
to_binary(Source) when is_atom(Source) -> atom_to_binary(Source, utf8);
to_binary(Source) when is_integer(Source) -> integer_to_binary(Source);
to_binary(Source) when is_binary(Source) -> Source;
to_binary(Source) when is_pid(Source) -> erlang:list_to_binary(pid_to_list(Source)).


md5(Value) ->
  lists:flatmap(fun(E) ->
    lists:map(fun(V) ->
      case V of _ when V == 10 -> $a;_ when V > 10 -> $a + (V - 10);_ when V < 10 -> $0 + V end
              end, [(E div 16), (E rem 16)])
                end, binary_to_list(erlang:md5(Value))).


page_data(Page,Count,PageData)->
  #{<<"page">>=>Page,
    <<"count">>=>Count,
    <<"items">>=>PageData
  }.

uuid(Seed)-> himq:md5(lists:concat(erlang:tuple_to_list(erlang:timestamp()) ++ erlang:pid_to_list(self())++Seed)).